import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart'; //dio插件，网络请求失败时自动重试
import 'package:rjpb/page/login/login_page.dart';
import 'package:rjpb/routes/z.dart';
import 'package:rjpb/shared/utils/storage_util.dart';
import 'package:rjpb/page/home/profile/apis/logout_api.dart';

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  factory HttpUtil() => _instance;
  late Dio _dio;
  final buffer = StringBuffer();

  HttpUtil._internal() {
    // application/x-www-form-urlencoded
    // multipart/form-data
    // application/json
    // text/xml
    BaseOptions options = BaseOptions(
      connectTimeout: const Duration(milliseconds: 20000),
      receiveTimeout: const Duration(milliseconds: 20000),
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
    );

    _dio = Dio(options);

    _dio.interceptors.add(RetryInterceptor(
      dio: _dio,
      logPrint: print,
      retries: 3,
      ignoreRetryEvaluatorExceptions: true,
      retryDelays: const [
        Duration(milliseconds: 200),
        Duration(milliseconds: 200),
        Duration(milliseconds: 200),
      ],
    ));
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          print("请求地址: ${options.path}");
          return handler.next(options); // 继续请求
        },
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          print("响应数据: ${response.data}");
          if (response.data is Map && response.data['code'] == 401) {
            print("服务器返回 401，跳转到登录页面");
            _handleUnauthorized();
            return handler.reject(
              DioException(
                requestOptions: response.requestOptions,
                type: DioExceptionType.badResponse,
                response: response,
                error: "Unauthorized (401)",
              ),
            );
          }
          return handler.next(response); // 正常处理响应
        },
        onError: (DioException e, ErrorInterceptorHandler handler) {
          print("请求错误111: ${e.message}");
          if (e.response?.statusCode == 401) {
            print("请求返回 401，跳转到登录页面");
            _handleUnauthorized();
          }
          return handler.next(e); // 继续处理错误
        },
      ),
    );
  }

  void _handleUnauthorized() {
    StorageUtil.clear();
    LogoutApi.logout();
    Get.offAllNamed(LoginPage.routeName);
  }

  Future get(
    String url, {
    Map<String, dynamic>? data,
    Map<String, dynamic>? headers,
    Options? options,
  }) async {
    return await request(
      url,
      queryParameters: data,
      method: HttpType.get.name,
      headers: headers,
      options: options,
    );
  }

  Future post(
    String url, {
    dynamic data,
    Map<String, dynamic>? headers,
    Options? options,
  }) async {
    return await request(
      url,
      data: data,
      method: HttpType.post.name,
      headers: headers,
      options: options,
    );
  }

  Future delete(
    String url, {
    Map<String, dynamic>? data,
    Map<String, dynamic>? headers,
    Options? options,
  }) async {
    return await request(
      url,
      queryParameters: data,
      method: HttpType.delete.name,
      headers: headers,
      options: options,
    );
  }

  Future put(
    String url, {
    Map<String, dynamic>? data,
    Map<String, dynamic>? headers,
    Options? options,
  }) async {
    return await request(
      url,
      queryParameters: data,
      method: HttpType.put.name,
      headers: headers,
      options: options,
    );
  }

  Future<Response> download(
    String urlPath,
    String savePath, {
    ProgressCallback? onReceiveProgress,
    CancelToken? cancelToken,
    Options? options,
  }) async {
    return await _dio.download(
      urlPath,
      savePath,
      cancelToken: cancelToken,
      options: options,
      onReceiveProgress: onReceiveProgress,
    );
  }

  Future request(
    String url, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Map<String, dynamic>? headers,
    Options? options,
    required String method,
  }) async {
    final Map<String, dynamic> defaultHeaders = {};

    if (headers != null) {
      defaultHeaders.addAll(headers);
    }

    // if (Uri.parse(url).path != "/auth/login" &&
    //     Uri.parse(url).host != "api.appcenter.ms") {
    //   defaultHeaders.addAll({
    //     "Authorization": "Bearer ${StorageUtil.getToken}",
    //   });
    //   print("Authorization Token: Bearer ${StorageUtil.getToken}");
    // }
    if (Uri.parse(url).path != "/auth/login" &&
        Uri.parse(url).host != "api.appcenter.ms") {
      // 修改这里：await 获取 token
      final token = await StorageUtil.getToken();
      print("实际使用的Token: $token"); // 调试用
      if (token.isNotEmpty) {
        defaultHeaders['Authorization'] = 'Bearer $token';
      }
    }

    final o = Options(
      method: method,
      headers: defaultHeaders,
      sendTimeout: options?.sendTimeout,
      receiveTimeout: options?.receiveTimeout,
    );
    final resp = await _dio.request(
      url,
      queryParameters: queryParameters,
      data: data,
      options: o,
    );
    return resp.data;
  }

  void _onError(DioException e, ErrorInterceptorHandler handler) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        print("请求连接超时啦~");
        break;
      case DioExceptionType.unknown:
        break;
      default:
        print(e.message ?? e.toString());
    }
  }
}

enum HttpType {
  get,
  post,
  delete,
  put,
}
